package com.berwin.utility;

import android.content.Context;
import android.content.SharedPreferences;

public class UserDefault {

    private static UserDefault _instance;

    private SharedPreferences sharedPreferences;

    private UserDefault() {
    }

    public void init(Context context) {
        sharedPreferences = context.getSharedPreferences("userdefault", Context.MODE_PRIVATE);
    }

    public static synchronized UserDefault getInstance() {
        if (_instance == null)
            _instance = new UserDefault();
        return _instance;
    }


    public void setValueForKey(String key, Object value) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        if (value instanceof Boolean) {
            editor.putBoolean(key, (Boolean) value);
        } else if (value instanceof String) {
            editor.putString(key, (String) value);
        } else if (value instanceof Float) {
            editor.putFloat(key, (Float) value);
        } else if (value instanceof Integer) {
            editor.putInt(key, (Integer) value);
        } else if (value instanceof Long) {
            editor.putLong(key, (Long) value);
        }
        editor.commit();
    }

    @SuppressWarnings("unchecked")
    public <T> T getValueForKey(String key, T def) {
        Object value = def;
        if (def instanceof Boolean) {
            value = sharedPreferences.getBoolean(key, (Boolean) def);
        } else if (def instanceof String) {
            value = sharedPreferences.getString(key, (String) def);
        } else if (def instanceof Float) {
            value = sharedPreferences.getFloat(key, (Float) def);
        } else if (def instanceof Integer) {
            value = sharedPreferences.getInt(key, (Integer) def);
        } else if (def instanceof Long) {
            value = sharedPreferences.getLong(key, (Long) def);
        }
        return (T) value;
    }
}
